package io.gitee.twoke.generator.engine.impl.cmd;

import io.gitee.twoke.generator.engine.impl.interceptor.Command;
import io.gitee.twoke.generator.engine.impl.interceptor.CommandContext;
import io.gitee.twoke.generator.engine.impl.persistence.entity.DataTableColumnEntity;
import io.gitee.twoke.generator.engine.impl.persistence.entity.DataTableColumnEntityManager;
import io.gitee.twoke.generator.engine.impl.persistence.entity.DataTableEntity;
import io.gitee.twoke.generator.engine.impl.persistence.entity.DataTableEntityManager;

public class DeleteTableCmd implements Command<Void> {

    private String key;
    private DeleteType deleteType;

    public DeleteTableCmd(String key, DeleteType deleteType) {
        this.key = key;
        this.deleteType = deleteType;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        DataTableColumnEntityManager tableColumnEntityManager = commandContext.getDataTableColumnEntityManager();
        DataTableEntityManager tableEntityManager = commandContext.getDataTableEntityManager();
        DataTableEntity tableEntity = null;
        DataTableColumnEntity columnEntity = tableColumnEntityManager.create();
        switch (deleteType) {
            case BY_TABLE_ID:
                tableEntity = tableEntityManager.create();
                tableEntity.setId(key);
                columnEntity.setTableId(key);
                break;
            case BY_TABLE_NAME:
                tableEntity = (DataTableEntity) tableEntityManager.findByTableName(key);
                columnEntity.setTableId(tableEntity.getId());
        }
        tableEntityManager.delete(tableEntity);
        tableColumnEntityManager.delete(columnEntity);
        return null;
    }

    public static enum DeleteType {
        BY_TABLE_ID,
        BY_TABLE_NAME
    }
}
